<?php

namespace app\api\controller;

use addons\third\library\Service;
use addons\third\model\Third;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'wxappLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', $this->auth->getUserinfo());
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $type = $this->request->post('type','mobile');
        $type = $type=='email'?'email':'mobile';
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if($type=='email' && empty($email)){
            $this->error(__('Invalid parameters'));
        }
        if($type=='mobile' && empty($mobile)){
            $this->error(__('Invalid parameters'));
        }

        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^\d{8,11}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if($type=='mobile'){
            $ret = Sms::check($mobile, $code, 'register');
            if (!$ret) {
             //   $this->error(__('Captcha is incorrect'));
            }
        }
        if($type=='email'){
            $ret = Ems::check($email, $code, 'register');
            if (!$ret) {
            //    $this->error(__('Captcha is incorrect'));
            }
        }

        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $nickname = $this->request->post('nickname');
        $telegram = $this->request->post('telegram');
        $wechat = $this->request->post('wechat');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($avatar != "") {
            $user->avatar = $avatar;
        }

        if ($mobile != "") {
            $user->mobile = $mobile;
        }

        if ($nickname != "") {
            $user->nickname = $nickname;
        }

        if ($telegram != "") {
            $user->telegram = $telegram;
        }

        if ($wechat != "") {
            $user->wechat = $wechat;
        }

        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }


    // 小程序登陆
    public function wxappLogin()
    {
        $code = $this->request->post("code");
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        $recommond = $this->request->post('recommond', 0, 'intval');
        if (!$code) {
            $this->error("参数不正确");
        }
        // 获取配置
        $config = get_addon_config('third');
        $config = [
            'app_id' => $config['wxapp']['app_id'],
            'secret' => $config['wxapp']['app_secret'],
            'response_type' => 'array',
        ];

        $app = Factory::miniProgram($config);
        $session = $app->auth->session($code);
        if (isset($session['errcode'])) {
            $this->error($session['errmsg']);
        }

        if (isset($session['openid'])) {
            $userInfo = $app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
            //如果有传Token
            $platform = 'wxapp';
            if(isset($userInfo['nickName']) && $userInfo['nickName'] == '微信用户'){
                $userInfo['nickName'] = "请完善个人信息";
            }
            $result = [
                'openid' => $session['openid'],
                'unionid' => isset($userInfo['unionId']) ? $userInfo['unionId'] : '',
                'userinfo' => [
                    'nickname' => filterEmoji($userInfo['nickName']),
                ],
                'access_token' => $session['session_key'],
                'refresh_token' => '',
                'expires_in' => isset($session['expires_in']) ? $session['expires_in'] : 0,
            ];
            //检测是否登录
            if ($this->auth->isLogin()) {
                $third = Third::where(['openid' => $session['openid'], 'platform' => 'wxapp'])->find();
                if ($third && $third['user_id'] == $this->auth->id) {
                    //把最新的 session_key 保存到 第三方表的 access_token 里
                    $third['access_token'] = $session['session_key'];
                    $third['unionid'] = isset($userInfo['unionId']) ? $userInfo['unionId'] : '';
                    $third->save();
                    $user = $this->auth->getUser();
                    $fields['gender'] = $userInfo['gender'];
                    $user->save($fields);
                    $this->success("登录成功", $this->auth->getUserinfo());
                } elseif ($third && $third['user_id'] !== $this->auth->id) {
                    $this->success("登录失败,该微信已存在,请直接使用微信授权登陆");
                } else {
                    $time = time();
                    $values = [
                        'platform' => $platform,
                        'openid' => $result['openid'],
                        'openname' => isset($result['userinfo']['nickname']) ? $result['userinfo']['nickname'] : '',
                        'access_token' => $result['access_token'],
                        'refresh_token' => $result['refresh_token'],
                        'expires_in' => $result['expires_in'],
                        'logintime' => $time,
                        'expiretime' => $time + $result['expires_in'],
                        'user_id' => $this->auth->id,
                    ];
                    $auth = Auth::instance();
                    $user = $auth->getUser();
                    $fields = ['username' => 'u' . $user->id];
                    if (isset($result['userinfo']['nickname'])) {
                        $fields['nickname'] = $result['userinfo']['nickname'];
                    }

                    if (isset($result['userinfo']['avatar'])) {
                        $fields['avatar'] = $result['userinfo']['avatar'];
                    }
                    if($fields['nickname'] == '微信用户'){
                        $fields['nickname'] = "请完善个人信息";
                    }
                    $fields['group_id'] = 0;
                    $fields['recommend'] = $recommond;
                    // 更新会员资料
                    $user->save($fields);
                    Third::create($values);
                    $userInfo = $auth->getUserinfo();
                    $this->success("登录成功", ['userInfo' => $userInfo]);
                }
            }

            $extend = [
                'gender' => $userInfo['gender'],
                'nickname' => filterEmoji($userInfo['nickName']),
                'avatar' => $userInfo['avatarUrl'],
                'recommend' => $recommond,
            ];
            $ret = Service::connect($platform, $result, $extend);
            if ($ret) {
                $auth = Auth::instance();
                $userinfo = $auth->getUserinfo();
                $this->success("登录成功", ['userinfo' => $userinfo]);
            } else {
                $this->error("连接失败");
            }
        } else {
            $this->error("获取openid失败");
        }
        $this->error("登录失败");
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function qrcode()
    {
        // 获取配置
        $config = get_addon_config('third');
        $config = [
            'app_id' => $config['wxapp']['app_id'],
            'secret' => $config['wxapp']['app_secret'],
            'response_type' => 'array',
        ];

        $app = Factory::miniProgram($config);
        $scene = $this->auth->id;
        $params = [
            'page' => 'pages/index/index',
            'check_path' => false,
            'env_version' => 'release', //正式版为 "release"，体验版为 "trial"，开发版为 "develop"。
            'width' => 280,
            'is_hyaline' => true,
        ];

        $userId = $this->auth->id;


        $response = $app->app_code->getUnlimit($scene, $params);
        $path = ROOT_PATH . 'public' . DS . 'qrcode';
        $appcode = $userId . '.png';

        $userSharePath = $path . DS . $appcode;
        if (!file_exists($userSharePath)) {
            $filename = "";
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs($path, $appcode);
            }

            if ($filename == "") {
                $this->error("生成二维码错误");
            }
        }

        $qrcodeThumbPath = $path . DS . $userId . "_thumb.png";
        if (!file_exists($qrcodeThumbPath)) {
            $qrcode = \think\Image::open($userSharePath);
            $qrcode->thumb(200, 200);
            $qrcode->save($qrcodeThumbPath);
        }


        //生成图片
        $backage = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'system' . DS . 'qrcode_backage_1.png';
        $savePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'share' . DS . $userId . "_share.png";
        $domain = $this->request->domain();
        if (file_exists($savePath)) {
            $this->success("操作成功", ['share_path' => $domain . '/uploads/share/' . $userId . "_share.png"]);
        }

        $image = \think\Image::open($backage);

        $local = [200, 740];
        $image->water($qrcodeThumbPath, $local); // $path 图片本地路径  $local 数组 [$x, $y];
        $image->save($savePath);

        $this->success("操作成功", ['share_path' => $domain . '/uploads/share/' . $userId . "_share.png"]);
    }

    public function recommend()
    {
        $userInfo = $this->auth->getUserInfo();
        $user = new \app\common\model\User();
        $list = $user->field(['id', 'username', 'avatar', 'group_id', 'nickname', 'createtime'])->order("id desc")->where(['recommend' => $userInfo['id']])->paginate()->each(function ($item, $key) {
            $item->createtime = date("Y-m-d H:i:s", $item->createtime);
        });

        $this->success(__('Operation completed'), $list);
    }
}
